package ru.positron;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

@SuppressWarnings("serial")
public class DescribeChangesetServlet extends HttpServlet {
	
	static Logger LOG = Logger.getLogger( OsmRssSpatialFilter.class.getName() );
	//private final static String server="http://api06.dev.openstreetmap.org/";
	private final static String server="http://openstreetmap.org/";
	
	private void initKml(PrintWriter wr) {
		wr.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
				"<kml xmlns='http://earth.google.com/kml/2.0'>\n");
		wr.println("<Style id='S_CREATE'>\n" +
				"\t<IconStyle><Icon> <href>img/point-green.png</href> </Icon></IconStyle>\n" +
				"\t<color>FF00FF00</color>\n" +
				"</Style>\n\n");
		wr.println("<Style id='S_MODIFY'>\n" +
				"\t<IconStyle><Icon> <href>img/point-blue.png</href> </Icon></IconStyle>\n" +
				"\t<color>FF00FF00</color>\n" +
				"</Style>\n\n");
		wr.println("<Style id='S_DELETE'>\n" +
				"\t<IconStyle><Icon> <href>img/point-red.png</href> </Icon></IconStyle>\n" +
				"\t<color>FF00FF00</color>\n" +
				"</Style>\n\n");
		
		
		wr.println("<Document>\n" +
				"<name>changeset desc</name>\n" +
				"<description>doc desc</description>\n" +
				"");
	}
	private void completeKml(PrintWriter wr) {
		wr.println("</Document>\n</kml>");
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String changeset = req.getParameter("changeset");
		if(changeset==null || changeset.length()==0) changeset="11733420";
		LOG.info("getting "+changeset);
		
		try {
			DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
	        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();	        
	        Document doc = docBuilder.parse(Utils.download( server+"api/0.6/changeset/"+changeset+"/download") );
	        resp.setContentType("text/plain");
	        //resp.setContentType("application/vnd.google-earth.kml+xml");
			PrintWriter wr = resp.getWriter();//.println("Hello, world");
	        //LOG.info("document loaded");
			//wr.println("doc loaded");
			initKml(wr);
	        Node node = doc.getFirstChild().getFirstChild();
	        while(node!=null) {
	        	if(node.getNodeType() == Node.ELEMENT_NODE) {
	        		//wr.println("processing node "+node);
	        		processNode(node, wr); 
	        	}
	        	node = node.getNextSibling();
	        } 
	        completeKml(wr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private enum Type { CREATE, MODIFY, DELETE;
		static DescribeChangesetServlet.Type getType(Node node) {
			if (node.getNodeName().equals("create")) return CREATE;
			if (node.getNodeName().equals("modify")) return MODIFY;
			if (node.getNodeName().equals("delete")) return DELETE;
			return MODIFY;
		}
	} 
	
	/** 
	 * 
	 * @param node
	 * @param wr
	 */
	private void processNode(Node node, PrintWriter wr) {
		LOG.info("Processing node "+node);
		Type t = Type.getType(node);
		
		Node createdNode = node.getFirstChild();
		while(createdNode!=null) {
			if(createdNode.getNodeType() == Node.ELEMENT_NODE) {
				String type = createdNode.getNodeName().intern(); 
				if(type == "node") {
					NamedNodeMap attrs = createdNode.getAttributes();
					try {
						double lat = Double.parseDouble(attrs.getNamedItem("lat").getNodeValue());
						double lon = Double.parseDouble(attrs.getNamedItem("lon").getNodeValue());
						//wr.println(" found <node> at "+lat+"/"+lon);
						wr.println("<Placemark id='"+attrs.getNamedItem("id").getNodeValue()+"'>");
						wr.println("\t<styleUrl>#S_"+t+"</styleUrl>");
						wr.println("\t<name>"+attrs.getNamedItem("user").getNodeValue()+"</name>");
						wr.println("\t<Point><coordinates>"+lon+","+lat+"</coordinates></Point>");
						//LOG.info("output node "+lat+"/"+lon);
						wr.println("</Placemark>");
					} catch(NullPointerException e) {  }
				}
				if(type == "way") {
					//wr.println(" found <way>");
				}
				if(type == "relation") {
					//wr.println(" found <way>");
				}
			}
			createdNode = createdNode.getNextSibling();
		}
	}
}
